﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Net.Mail;
using System.Text.RegularExpressions;
/******************************************************    
程序名称:Function
Copyright  (c)  2006 RainStock 公司技术开发部
程序作者: jingjie
创建日期:2006-10-25
最后修改:2006-10-25
程序用途:实现全局功能函数
程序备注:
 * 全局通用函数类
 * 用来存放程序中的公用函数
 * 请放在App_Code目录
******************************************************/
/// <summary>
/// 通用函数类
/// </summary>
public class Function
{
	public Function()
	{
		//
		// TODO: 在此处添加构造函数逻辑
		//
	}

    /// <summary>
    ///MD5加密字符串
    /// </summary>
    public static string MD5(string str)
    {
        return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
    }


    /// <summary>
    ///生成随机验证代码,长度由length控制
    /// </summary>
    public static string Ran(int length)
    {
        int number;
        char code;
        string checkCode = String.Empty;
        System.Random random = new Random();
        for (int i = 0; i < length; i++)
        {
            number = random.Next();
            if (number % 2 == 0)
                code = (char)('0' + (char)(number % 10));
            else
                code = (char)('A' + (char)(number % 26));

            checkCode += code.ToString();
        }

        return checkCode;
    }


    /// <summary>
    ///检查是否完全有数字组成
    /// </summary>
    public static bool IsNumeric(string str)
    {   
        System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[-]?\d+[.]?\d*$");
        return reg1.IsMatch(str);
    }

    /// <summary>
    ///检查邮件地址的有效性
    /// </summary>
    public static bool IsValidEmail(string strIn)
    {
        return System.Text.RegularExpressions.Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
    }


    /// <summary>
    /// 检查IP地址的有效性 
    /// </summary>
    /// <param name="ip"></param>
    /// <returns></returns>
    public static bool IsValidIP(string ip)
    {
        if (System.Text.RegularExpressions.Regex.IsMatch(ip, "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"))
        {
            string[] ips = ip.Split('.');
            if (ips.Length == 4 || ips.Length == 6)
            {
                if (System.Int32.Parse(ips[0]) < 256 && System.Int32.Parse(ips[1]) < 256 & System.Int32.Parse(ips[2]) < 256 & System.Int32.Parse(ips[3]) < 256)
                    return true;
                else
                    return false;
            }
            else
                return false;

        }
        else
            return false;
    } 

    /// <summary>
    /// 截取指定长度的字符串
    /// </summary>
    public static string CutStr(string str, int length)
    {
        if (str.Length < length)
            return str;
        length = length * 2 - 3;
        int i = 0, j = 0;
        foreach (char chr in str)
        {
            if ((int)chr > 127)
                i += 2;
            else
                i++;

            if (i > length)
            {
                str = str.Substring(0, j) + "...";
                break;
            }
            j++;
        }
        return str;

    }


    /// <summary>
    /// Function.FormatDateTime(DateTime.Parse(Str));
    /// 将时间格式成 2006年11月8日 样式
    /// </summary>
    public static string FormatDateTime(DateTime Time)
    {
        return Time.Year + "年" + Time.Month+ "月" + Time.Day+ "日";
    }

    /// <summary>
    /// Function.FormatDateTimeMin(DateTime.Parse(Str));
    /// 将时间格式成 2006.11.8 样式
    /// </summary>
    public static string FormatDateTimeMin(DateTime Time)
    {
        return Time.Year + "." + Time.Month + "." + Time.Day ;
    }


 /*********************************************
 * PostMail(邮件地址，邮件标题，邮件内容[，附件列表])
 * 发送邮件功能函数  
********************************************/
    public static bool PostMail(string PostTOMail, string MailTitle, string MailBody, params  string[] PostFile)
    {
        string SmtpMailUser = ConfigurationManager.AppSettings["SmtpMailUser"].ToString();        //发件箱帐户
        string SmtpMailPWD = ConfigurationManager.AppSettings["SmtpMailPWD"].ToString();                      //该帐户对应的密码
        string SmtpMailHost = ConfigurationManager.AppSettings["SmtpMailHost"].ToString();          //邮件服务器
        
        //string SmtpMailUser = "jingjie@rainstock.cn";        //发件箱帐户
        //string SmtpMailPWD = "*******";                      //该帐户对应的密码
        //string SmtpMailHost = "mail.rainstock.cn";          //邮件服务器


        MailMessage MSG = new MailMessage();
        MSG.From = new MailAddress(SmtpMailUser);
        MSG.To.Add(PostTOMail);
        MSG.Subject = MailTitle;
        MSG.IsBodyHtml = true;
        MSG.Body = MailBody;

        //参数容错
        if (PostFile.GetType() == typeof(string))
            for (int i = 0; i < PostFile.LongLength; i++)
                //Attachment Data = new Attachment(PostFile);

                MSG.Attachments.Add(new Attachment(PostFile[i]));

        SmtpClient sc = new SmtpClient();
        //sc.EnableSsl = true;              //是否SSL加密
        sc.Host = SmtpMailHost;             //邮件服务器
        sc.Port = 25;                       //smtp端口
        sc.Credentials = new NetworkCredential(SmtpMailUser, SmtpMailPWD);
        //邮件发送报告
        try
        {
            sc.Send(MSG);
            return true;
        }
        catch
        {
            return false;

        }

    }
    public static string HtmlEnCode(string str)
    {
        str = str.Replace("<p>&nbsp;</p>", "");
        str = str.Replace("&", "&amp;");
        str = str.Replace("<", "&lt;");
        str = str.Replace(">", "&gt;");
        str = str.Replace("'", "''");
        str = str.Replace("*", "");
        str = str.Replace("\n\r", "<br/>");
        str = str.Replace("\n", "");
        str = str.Replace("\r", "");
        //str   =   str.Replace("?","");   
        str = str.Replace("insert", "");
        str = str.Replace("update", "");
        str = str.Replace("delete", "");
        str = str.Replace("create", "");
        str = str.Replace("drop", "");
        str = str.Replace("delcare", "");
        str = str.Replace("   ", "&nbsp;");

        str = str.Trim();
        if (str.Trim().ToString() == "")
            str = "";
        return str;
    }

    /// <summary>
    /// 显示被编码的HTML字符的 \ , < , > , &
    /// </summary>

    public static string ShowHtml(string Html)
    {
        Html = Html.Replace("&amp;", "&");
        Html = Html.Replace("&quot;", "\"");
        Html = Html.Replace("&lt;", "<");
        Html = Html.Replace("&gt;", ">");
        return Html;
    }

    public static string ClearHTML(string Html)
    {
        Html = Regex.Replace(Html, "<[^>]+>", "");
        Html = Html.Replace("&amp;", "&");
        Html = Html.Replace("&ldquo;", "“");
        Html = Html.Replace("&rdquo;", "”");
        Html = Regex.Replace(Html, "&lt;[^&gt;]+&gt;", "");
        return Html;
    }

    /// <summary>
    /// 返回用户的IP地址
    /// </summary>
    /// <returns></returns>
    public static string GetIP()
    {
        if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
        {
            return System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        }
        else
        {
            return System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
        } 

    }

    /// <summary>
    /// 比较两个时间的差值
    /// </summary>
    /// <param name="DT1">时间1</param>
    /// <param name="DT2">时间2</param>
    /// <param name="Methods">比较的类型：YY 年  DD 天 HH 小时 MM 分钟  SS 秒</param>
    /// <returns></returns>

    public static int ComparisonOfTime(DateTime DT1, DateTime DT2, string Methods)
    {
        double  ReturnValue = 0;
        int ThisValue = 0;
        TimeSpan TempTime = DT1 - DT2;
        switch (Methods)
        {
            case "YY": ReturnValue = TempTime.TotalDays / 360; break;
            case "DD": ReturnValue = TempTime.TotalDays; break;
            case "HH": ReturnValue = TempTime.TotalHours; break;
            case "MM": ReturnValue = TempTime.TotalMinutes; break;
            case "SS": ReturnValue = TempTime.TotalSeconds; break;
        }
           ThisValue =  Convert.ToInt32(ReturnValue);
        return ThisValue;
    }

    /// <summary>
    /// 取得文件的扩展名
    /// </summary>
    /// <param name="FileNameStr">文件名</param>
    /// <returns>扩展名( .ext )</returns>
    public static string GetFileExt(string FileNameStr)
    {
        return FileNameStr.Substring(FileNameStr.LastIndexOf('.'), FileNameStr.Length - FileNameStr.LastIndexOf('.'));
    }
    /// <summary>
    /// 接受URL参数
    /// </summary>
    /// <param name="StrName">字段名</param>
    /// <returns>参数值</returns>
    public static string QS(string StrName)
    {
        if (System.Web.HttpContext.Current.Request.QueryString[StrName] != null)
            return System.Web.HttpContext.Current.Request.QueryString[StrName].ToString();
        else
            return string.Empty;
    }

    /// <summary>
    /// 接收字符型URL参数
    /// </summary>
    /// <param name="StrName"></param>
    /// <returns></returns>
    public static string QSToStr(string StrName)
    {

        return ClearHTML(QS(StrName));
    }

    /// <summary>
    /// 接受整型的URL参数
    /// </summary>
    /// <param name="StrName"></param>
    /// <returns></returns>
    public static int QSToInt(string StrName)
    {
        int ReturnValue = 0;
        try
        {
            ReturnValue = Convert.ToInt32(QS(StrName));

        }
        catch
        {
            //Djj.ShowErr("系统错误", "类型转换异常！ <br />  Convert   string To Int32 Err");
        }
        finally
        {
        }
        return ReturnValue;
    }
}
